package cn.xiaopengstack.trigger.job;

import cn.xiaopengstack.domain.trade.service.ITradeSettlementOrderService;
import cn.xiaopengstack.types.enums.RedisKeyEnum;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author jiangyangang
 */
@Service
@Slf4j
public class GroupBuyNotifyJob {

    @Resource
    private ITradeSettlementOrderService tradeSettlementOrderService;

    @Resource
    private RedissonClient redissonClient;


    @Scheduled(cron = "0 0 0 * * ?")
    public void exec(){
        // 分布式互斥锁
        RLock lock = redissonClient.getLock(RedisKeyEnum.settlement_task_lock.getKey());

        try {
            boolean locked = lock.tryLock(3, 0, TimeUnit.SECONDS);
            if (!locked) {
                return;
            }

            Map<String, Integer> result = tradeSettlementOrderService.executeSettlementNotifyJob();
            log.info("结算通知定时任务，回调通知拼团结算结果 result:{}", JSONObject.toJSONString(result));
        } catch (Exception e) {
            log.error("结算通知定时任务，回调通知执行失败!", e);
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

}
